package com.zhn.usermanager.alibabapay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
@Controller
public class TestPayController {
    @RequestMapping("/pay")
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, AlipayApiException {
        // alipay测试支付地址   生产环境支付地址为https://openapi.alipay.com/gateway.do
        String serverURL = "https://openapi.alipaydev.com/gateway.do";
        // 创建的应用ID
        String APP_ID = "2021000118615326";
        // 自己的2048应用私钥
        String mKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmoSTP5qDQMNLkLjb1Ce/VgNI2hQ8n6aCkcTGK7G4fdUw+urw4TnyKDULlfkTrVdtPPtiDmzIfRbpNMTgIONFwxBkSDMiuQczV2PQsPlBYvwkrFe21nOCCanpm2gJy7NvUJxTasTqOaz7lEpvu2sB+BEzspscGkwJEFXPe9cJS7NTIW0e4nfS9w8cBuh2Cs1JCmMRLceMmI+wEGQRCvKyxHBOxSDou47AuSzWXgihWfD+ivOnlAOvcmEifNyPJem9wcAw60efn8onYcAH7Pp9xQFx2fxy3jamGIPTnwepqfZiLl6b+5tovOhjmdJhSztZPUybFLDb1/MO1UMRo9ukNAgMBAAECggEBAKPeR/iZg78atNuoQ23Z9t4OES2Cz7Pdw5jUpPdNqsMPNQtf02jAbyPJBOfytM6HoeUeFgnfX3x3s07kv4j+b6Kph0pD/ju5BDuuX/r+0T9lqBuSNjLr87LuCjAJ6GyjWVEbmhu0PbT/7VuUYHuW78U+b3QwU/y4KHtSaaB0KkYnes5TQ8iBrLGSDruJsslYSSzMCmQNMmYlGQdIu0BuBWz7tCoRoBA01iX7Y3pof/Ub4Y3ag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Tx4f1I/xUSpi1S1hdcmv5Eerh8EhvwCSQNCbCdhoqPNmt9zYVKJw3QiLQaQuETfDC8EtBFH+zUupdbgOtMYwPdk/x/3o+8LHWcJG5pqeDE4Vw72cO+vLc4PlJAktuG7BmeEJS3YihOIkeMZ6UgMFEzBYuj8o6E6eV8/fpUavHCnRL0Y5o8LizifdHTyd/AnWvu/+fBSiL5CkKj8Va7OvXvDeYA8iSn8i2Enm/cNOj36f5svv8MdL7AyFc/D2r6jCMZs8/qthkS3rmwf1j1vRbg0P/SuodGHXmZWvI9d1dup1aDsIQEQnWGFLAvQHQIDAQAB";
        //  获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(serverURL, APP_ID,
                mKey, "json", "UTF-8", aKey, "RSA2");
        //  创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 用户确认支付后，支付宝get请求returnUrl
        alipayRequest.setReturnUrl("http://localhost:8080/success.html");
        // 交易成功后，支付宝post请求notifyUrl（商户入参传入）
        alipayRequest.setNotifyUrl("http://localhost:8080/payReturnServlet");
        /*
            由于同步返回的不可靠性，支付结果必须以异步通知或查询接口返回为准，不能依赖同步跳转。
            商户系统接收到异步通知以后，必须通过验签（验证通知中的sign参数）来确保支付通知是由支付宝发送的。
         */

        /*
             填充业务参数
                 out_trade_no   每笔订单号需要自身的唯一id，支付宝会根据此id判断是否交易
                 total_amount   这笔订单的价格
                 subject        订单商品名称
                 product_code   支付方式：QUICK_WAP_PAY 登录账号支付
             这四个参数应该从结算页面传递过来
         */
        // 每笔订单号需要自身的唯一id，支付宝会根据此id判断是否交易
        // 订单号一旦支付成功，永久在此应用中不可使用
        String out_trade_no = "DX" + System.currentTimeMillis();
        // 这笔订单的价格
        String total_amount = "11888.88";
        // 订单商品名称
        String subject = "Iphone6 16G";
        // 支付方式：QUICK_WAP_PAY 登录账号支付
        String product_code = "QUICK_WAP_PAY";

        // 生成支付json数据
        String bizContent = "{" +
                "\"out_trade_no\":\"" + out_trade_no + "\"," +
                "\"total_amount\":" + total_amount + "," +
                "\"subject\":\"" + subject + "\"," +
                "\"product_code\":\"" + product_code + "\"}";
        System.out.println("支付生成json数据 bizContent=" + bizContent);

        // 提交支付请求
        alipayRequest.setBizContent(bizContent);

        // 调用SDK生成表单
        String form = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        // 直接将完整的表单html输出到页面
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
